import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import '../../network/Api.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';
import 'chat_list/chage_message_list_page.dart';

class MessageUi extends StatefulWidget {
  const MessageUi({Key? key}) : super(key: key);

  @override
  State<MessageUi> createState() => _MessageUiState();
}

class _MessageUiState extends State<MessageUi> {
  List<EMConversation> lists = [];
  late EMMessage emMessage;
  final player = AudioPlayer();

//加载的页数
  bool isLoading = false; //是否正在加载数据
  final _regExp = r"^[a-z0-9_]+$";
  List addmessage = [];

  late EMConversation? conversation;

  final ScrollController scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getMoreWidget();
      }
    });
    _addChatListener();
    initdata();
    setState(() {});
  }

  void setMessagelist(List addmessage) async {
    if (Provider.userEaseName.isEmpty || addmessage.isEmpty) return;
    //--类型 （1：消息，2：好友，3：粉丝，4：群聊， 5：新朋友）
    final res = await Api.getInstance()
        .addMessagelist(Provider.userEaseName, addmessage, "1");

    if (res['code'] == 0) {
    } else {
      toast(res['msg']);
    }
  }

  void initdata() async {
    //获取所有未读消息数
    int unreadCount =
        await EMClient.getInstance.chatManager.getUnreadMessageCount();
    print('zz  $unreadCount');

    lists = await EMClient.getInstance.chatManager
        .fetchConversationListFromServer();
    print('cccc ${lists.length}');
    if (lists.isNotEmpty) {
      addmessage.clear();
      for (int a = 0; a < lists.length; a++) {
        print('zzz ${lists[a].type}');
        addmessage.add(lists[a].id);
        await EMClient.getInstance.chatManager.getConversation(
          lists[a].id,
          type: lists[a].type,
          createIfNeed: true,
        );

        // int? unreadCount = await conversation?.unreadCount();
        // print('fff $unreadCount');
      }
      //setMessagelist(addmessage);
    }
    setState(() {});
  }

  void _addChatListener() {
    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      // "YXA6wcWSSBC_S3KH03JNFHHfrA",
      'YXA6hl6vye2MTQOb2k-1mAKAiA',
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          player.setAsset('images/music_reveice.mp3');
          final session = await AudioSession.instance;
          session.configure(const AudioSessionConfiguration.music());
          player.play();
          for (var msg in messages) {
            switch (msg.body.type) {
              case MessageType.TXT:
                {
                  EMTextMessageBody body = msg.body as EMTextMessageBody;
                  // EMClient.getInstance.chatManager.loadAllConversations();
                  EMClient.getInstance.chatManager.updateMessage(msg);
                  initdata();
                  // emMessage?.latestMessage();
                  // widget.emMessage?.updateMessage(msg);

                  // _addLogToConsole(
                  //   "收到文字消息: ${body.content}, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.IMAGE:
                {
                  // _addLogToConsole(
                  //   "收到图片信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.VIDEO:
                {
                  // _addLogToConsole(
                  //   "收到视频信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.LOCATION:
                {
                  // _addLogToConsole(
                  //   "收到位置信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.VOICE:
                {
                  EMVoiceMessageBody body = msg.body as EMVoiceMessageBody;
                  if (kDebugMode) {
                    print('------------------' + body.localPath);
                  }
                  // EMClient.getInstance.chatManager.loadAllConversations();
                  EMClient.getInstance.chatManager.updateMessage(msg);
                  initdata();
                }
                break;
              case MessageType.FILE:
                {
                  // _addLogToConsole(
                  //   "收到图片信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.CUSTOM:
                {
                  // _addLogToConsole(
                  //   "接受自定义信息, from: ${msg.from}",
                  // );
                }
                break;
              case MessageType.CMD:
                {
                  // 当前回调中不会有 CMD 类型消息，CMD 类型消息通过 `EMChatEventHandler#onCmdMessagesReceived` 回调接收
                }
                break;
            }
          }
        },
      ),
    );
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {
      initdata();
    });
  }

  /// 加载更多时显示的组件,给用户提示
  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(
          color: Colors.white, //修改颜色
        ),
        elevation: 0,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: const Text(
          "消息",
          style: TextStyle(
              color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold),
        ),
      ),
      body: lists.isNotEmpty
          ? RefreshIndicator(
              onRefresh: _onRefresh,
              child: ListView.builder(
                controller: scrollController,
                itemBuilder: (_, index) {
                  if (lists.isNotEmpty) {
                    return MessageData(lists[index]!);
                  } else {
                    return Container();
                  }
                },
                itemCount: lists.length,
              ),
            )
          : SizedBox(
              height: 500,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Center(
                    child: Image.asset(
                      'images/ic_nomessage.png',
                      width: 175,
                      height: 122,
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}


